package org.jeecg.modules.reserve.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

public class QiniuUpload {
    /**
     * 这两个登录七牛 账号里面可以找到
     **/
    private static String ACCESS_KEY = VariableName.ACCESS_KEY;

    private static String SECRET_KEY = VariableName.SECRET_KEY;
    /**
     * 对应要上传到七牛上 你的那个路径（自己建文件夹 注意设置公开）
     **/
    private static String BUCKET_NAME = VariableName.BUCKET;
    /**
     * 密钥配置
     **/
    private static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    private static Configuration cfg = new Configuration(Zone.huanan());
    /**
     * 创建上传对象
     **/
    private static UploadManager uploadManager = new UploadManager(cfg);

    /**
     * 简单上传，使用默认策略，只需要设置上传的空间名就可以了
     **/
    public static String getUpToken() {
        return auth.uploadToken(BUCKET_NAME);
    }

    public static String uploadPic(String filePath, String fileName) {
        Configuration cfg = new Configuration(Zone.huanan());
        UploadManager uploadManager = new UploadManager(cfg);
        //AccessKey的值
        String accessKey = ACCESS_KEY;
        //SecretKey的值
        String secretKey = SECRET_KEY;
        //存储空间名
        String bucket = BUCKET_NAME;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(filePath, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return VariableName.DOMAIN + putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return null;
    }

    public static String updateFile(MultipartFile file, String filename) throws Exception {
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        try {
            InputStream inputStream = file.getInputStream();
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            //buff用于存放循环读取的临时数据
            byte[] buff = new byte[600];
            int rc;
            while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }

            byte[] uploadBytes = swapStream.toByteArray();
            try {
                Response response = uploadManager.put(uploadBytes, filename, getUpToken());
                //解析上传成功的结果
                DefaultPutRet putRet;
                putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                return VariableName.DOMAIN + putRet.key;

            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ignored) {
                }
            }
        } catch (UnsupportedEncodingException ignored) {
        }
        return null;
    }

    /**
     * 获取私有空间下载文件路径
     *
     * @return
     */
    public static String getDownloadUrl(String targetUrl) {
        String downloadUrl = auth.privateDownloadUrl(targetUrl);
        return downloadUrl;
    }

    /**
     * 主函数
     * @param args
     */
    public static void main(String[] args) {
        //构造私有空间的需要生成的下载的链接；
        //格式： http://私有空间绑定的域名/空间下的文件名
        String targetUrl = "http://qa9mycwyz.bkt.clouddn.com/9c0166cb16474631bd475240a1b75bf1.jpg";
        String downloadUrl = getDownloadUrl(targetUrl);
        System.out.println(downloadUrl);

    }
}